"use strict";

import Vue from "vue";
import axios from "axios";
import router from "../router/index";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.baseURL = "/api";
let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    let token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `token ${token}`;
    }
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    switch (response.data.status) {
      case 200: return response;
      case 401:
        alert(response.data.msg + "\n即将跳转到登录界面...");
        setTimeout(() => {
          router.replace({ path: '/login', query: { redirect: router.currentRoute.fullPath } })
        }, 2);
        break;
      default: alert(response.data.msg);
    };
    return response;
  },
  function(error) {
    // Do something with response error
    if (error.response) {
      // todo 
      switch (error.response.status) {
        // 如果返回401，则清除token信息并跳转到登录页面
        case 401:
          router.replace({ path: '/login', query: { redirect: router.currentRoute.fullPath }})
      }
    }
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  console.log(options);
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    }
  });
};

Vue.use(Plugin);

export default Plugin;
